package mcp

import (
	"fmt"
	"project-info/src/model"

	"project-info/src/lib")

// 资源列表处理
func handleResourcesList(msg *MCPMessage) *MCPMessage {
	resources := []MCPResource{
		{
			URI:         "project://gitlab/projects",
			Name:        "GitLab Projects",
			Description: "所有GitLab项目列表",
			MimeType:    "application/json",
		},
		{
			URI:         "project://jenkins/builds",
			Name:        "Jenkins Builds",
			Description: "Jenkins构建历史",
			MimeType:    "application/json",
		},
		{
			URI:         "project://system/config",
			Name:        "System Configuration",
			Description: "系统配置信息",
			MimeType:    "application/json",
		},
		{
			URI:         "project://servers/list",
			Name:        "Server List",
			Description: "服务器列表",
			MimeType:    "application/json",
		},
	}

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      msg.ID,
		Result: map[string]interface{}{
			"resources": resources,
		},
	}
}

// 资源读取处理
func handleResourcesRead(c *lib.GinContext, msg *MCPMessage) *MCPMessage {
	params, ok := msg.Params.(map[string]interface{})
	if !ok {
		return createErrorResponse(msg.ID, -32602, "Invalid params")
	}

	uri, ok := params["uri"].(string)
	if !ok {
		return createErrorResponse(msg.ID, -32602, "Missing URI")
	}

	switch uri {
	case "project://gitlab/projects":
		return readGitlabProjects(msg.ID)
	case "project://jenkins/builds":
		return readJenkinsBuilds(msg.ID)
	case "project://system/config":
		return readSystemConfig(msg.ID)
	case "project://servers/list":
		return readServersList(msg.ID)
	default:
		return createErrorResponse(msg.ID, -32601, "Unknown resource URI: "+uri)
	}
}

// 读取GitLab项目
func readGitlabProjects(id interface{}) *MCPMessage {
	var repos []model.GitlabRepo
	result := model.DB().Find(&repos)
	if result.Error != nil {
		return createErrorResponse(id, -32603, "Database error: "+result.Error.Error())
	}

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      id,
		Result: map[string]interface{}{
			"contents": []map[string]interface{}{
				{
					"uri":      "project://gitlab/projects",
					"mimeType": "application/json",
					"text":     fmt.Sprintf("%+v", repos),
				},
			},
		},
	}
}

// 读取Jenkins构建
func readJenkinsBuilds(id interface{}) *MCPMessage {
	var builds []model.JenkinsJobBuild
	result := model.DB().Limit(20).Order("id desc").Find(&builds)
	if result.Error != nil {
		return createErrorResponse(id, -32603, "Database error: "+result.Error.Error())
	}

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      id,
		Result: map[string]interface{}{
			"contents": []map[string]interface{}{
				{
					"uri":      "project://jenkins/builds",
					"mimeType": "application/json",
					"text":     fmt.Sprintf("%+v", builds),
				},
			},
		},
	}
}

// 读取系统配置
func readSystemConfig(id interface{}) *MCPMessage {
	config := map[string]interface{}{
		"gitlab_api_url": model.C.General.GitlabApiUrl,
		"jenkins_url":    model.C.General.JenkinsUrl,
		"repo_url":       model.C.General.RepoUrl,
		"base_path":      model.C.General.BasePath,
	}

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      id,
		Result: map[string]interface{}{
			"contents": []map[string]interface{}{
				{
					"uri":      "project://system/config",
					"mimeType": "application/json",
					"text":     fmt.Sprintf("%+v", config),
				},
			},
		},
	}
}

// 读取服务器列表
func readServersList(id interface{}) *MCPMessage {
	var servers []model.Server
	result := model.DB().Find(&servers)
	if result.Error != nil {
		return createErrorResponse(id, -32603, "Database error: "+result.Error.Error())
	}

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      id,
		Result: map[string]interface{}{
			"contents": []map[string]interface{}{
				{
					"uri":      "project://servers/list",
					"mimeType": "application/json",
					"text":     fmt.Sprintf("%+v", servers),
				},
			},
		},
	}
}

// 提示词列表处理
func handlePromptsList(msg *MCPMessage) *MCPMessage {
	prompts := []map[string]interface{}{
		{
			"name":        "devops_assistant",
			"description": "DevOps运维助手提示词",
			"arguments": []map[string]interface{}{
				{
					"name":        "task_type",
					"description": "任务类型 (deployment, monitoring, troubleshooting)",
					"required":    true,
				},
				{
					"name":        "environment",
					"description": "环境 (dev, test, prod)",
					"required":    false,
				},
			},
		},
		{
			"name":        "jenkins_helper",
			"description": "Jenkins构建助手提示词",
			"arguments": []map[string]interface{}{
				{
					"name":        "job_name",
					"description": "Jenkins任务名称",
					"required":    true,
				},
			},
		},
	}

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      msg.ID,
		Result: map[string]interface{}{
			"prompts": prompts,
		},
	}
}

// 获取提示词处理
func handlePromptsGet(c *lib.GinContext, msg *MCPMessage) *MCPMessage {
	params, ok := msg.Params.(map[string]interface{})
	if !ok {
		return createErrorResponse(msg.ID, -32602, "Invalid params")
	}

	name, ok := params["name"].(string)
	if !ok {
		return createErrorResponse(msg.ID, -32602, "Missing prompt name")
	}

	arguments, _ := params["arguments"].(map[string]interface{})

	switch name {
	case "devops_assistant":
		return getDevOpsAssistantPrompt(msg.ID, arguments)
	case "jenkins_helper":
		return getJenkinsHelperPrompt(msg.ID, arguments)
	default:
		return createErrorResponse(msg.ID, -32601, "Unknown prompt: "+name)
	}
}

// DevOps助手提示词
func getDevOpsAssistantPrompt(id interface{}, args map[string]interface{}) *MCPMessage {
	taskType, _ := args["task_type"].(string)
	environment, _ := args["environment"].(string)

	prompt := fmt.Sprintf(`你是一个专业的DevOps运维助手，专门帮助管理和操作项目信息系统。

当前任务类型: %s
目标环境: %s

你可以执行以下操作：
1. 查询GitLab项目信息
2. 获取Jenkins构建状态
3. 执行SSH命令
4. 触发流水线构建
5. 监控系统状态

请根据用户的需求，选择合适的工具来完成任务。始终保持专业和准确。`, taskType, environment)

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      id,
		Result: map[string]interface{}{
			"description": "DevOps运维助手",
			"messages": []map[string]interface{}{
				{
					"role": "user",
					"content": map[string]interface{}{
						"type": "text",
						"text": prompt,
					},
				},
			},
		},
	}
}

// Jenkins助手提示词
func getJenkinsHelperPrompt(id interface{}, args map[string]interface{}) *MCPMessage {
	jobName, _ := args["job_name"].(string)

	prompt := fmt.Sprintf(`你是一个Jenkins构建助手，专门帮助管理Jenkins任务。

当前关注的任务: %s

你可以：
1. 查询构建历史和状态
2. 触发新的构建
3. 分析构建失败原因
4. 提供构建优化建议

请根据用户需求提供专业的Jenkins相关帮助。`, jobName)

	return &MCPMessage{
		JSONRPC: "2.0",
		ID:      id,
		Result: map[string]interface{}{
			"description": "Jenkins构建助手",
			"messages": []map[string]interface{}{
				{
					"role": "user",
					"content": map[string]interface{}{
						"type": "text",
						"text": prompt,
					},
				},
			},
		},
	}
}
